package com.example.desionMode.bank.oop;

import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Comparator;

/**
 * @author houyangfan
 * @version 1.0
 * @date 2022/8/5 14:09
 */
@Slf4j
public class BankService {


    public static String remoteReq(AbstractApi abstractApi) {

        // 通过注解获取到该次请求的url
        BankApi bankApi = abstractApi.getClass().getAnnotation(BankApi.class);
        String url = bankApi.url();

        StringBuilder stringBuilder = new StringBuilder();
        Arrays.stream(abstractApi.getClass().getDeclaredFields())
                .filter(field -> field.isAnnotationPresent(BankField.class)) // 筛选标记注解的字段
                .sorted(Comparator.comparing(a -> a.getAnnotation(BankField.class).order())) // 根据注解的order字段排序
                .peek(field -> field.setAccessible(true))
                .forEach(field -> {
                    BankField fieldAnnotation = field.getAnnotation(BankField.class);
                    Object value = "";
                    try {
                        value = field.get(abstractApi);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                    switch (fieldAnnotation.type()) {
                        case "S": {
                            stringBuilder.append(String.format("%-" + fieldAnnotation.length() + "s", value.toString()).replace(" ", "_"));
                            break;
                        }
                        case "N": {
                            stringBuilder.append(String.format("%0" + fieldAnnotation.length() + "d", Integer.valueOf(value.toString())));
                            break;
                        }
                        case "B": {
                            stringBuilder.append(String.format("%0" + fieldAnnotation.length() + "d",
                                    new BigDecimal(value.toString()).setScale(2, RoundingMode.DOWN)
                                            .multiply(new BigDecimal("100")).longValue()));
                            break;
                        }
                        default:
                        break;
                    }
                });
        log.error("当前请求url为：{}", url);
        return stringBuilder.toString();

    }

    public static void main(String[] args) {
        CreateUserApi userApi = new CreateUserApi();
        CreatePayApi createPayApi = new CreatePayApi();

        userApi.setAge(30);
        userApi.setIdCard("130198199811020033");
        userApi.setMobile("19831021792");
        userApi.setName("audy");
        userApi.setAddress("北京市");
        System.out.println(remoteReq(userApi));

        createPayApi.setAmount(new BigDecimal("33.22"));
        createPayApi.setUid(32124);
        System.out.println(remoteReq(createPayApi));
    }
}
